/**
 * 应用到VUE组件\src\layout\components\TagsView\index.vue
 */
import useTagsViewStore from '@/store/tagsViewStore.ts'
import router from '@/router'
import { RouteLocationNormalizedLoaded,useRouter } from 'vue-router'


export const tab = {
  
  // 刷新当前tab页签
  /**
   * 
      删除缓存视图
      nextTick等待DOM更新完成
      执行路由替换
      调用回调函数
   */


  refreshPage:async (view: RouteLocationNormalizedLoaded | undefined,callback?: () => void) => {
  let resolvedView = view; // 使用一个新变量，避免直接修改参数

  if (resolvedView === undefined) {
    const currentRoute = useRouter().currentRoute.value;
    const { matched: currentMatched } = currentRoute;
    // 使用find而不是forEach，找到第一个匹配的组件
    const matchedRecord = currentMatched.find((m) => {
      return m.components && m.components.default && m.components.default.name &&
        !['Layout', 'ParentView'].includes(m.components.default.name);
    });

    if (matchedRecord && matchedRecord.components && matchedRecord.components.default) {
      resolvedView = {
        ...currentRoute,
        name: matchedRecord.components.default.name,
      };
    } else {
      // 如果没有找到合适的组件，我们可以使用当前路由，或者抛出一个错误
      // 这里我们使用当前路由
      resolvedView = currentRoute;
    }
  }

  // 现在 resolvedView 肯定有值
  useTagsViewStore().delCachedView(resolvedView);

  const { path, query } = resolvedView;
  await nextTick();
  router.replace({
    path: '/redirect' + path,
    query: query
  });

  // 调用回调函数（如果提供了）
  callback?.();
},



  // 关闭当前tab页签，打开新页签
  closeOpenPage(view: RouteLocationNormalizedLoaded | undefined,callback?: () => void) {
    if (view?.meta?.affix) return
    useTagsViewStore().delView(view || unref(useRouter().currentRoute))
    callback?.()
  },



  // 关闭指定tab页签
  closeSelectedPage(view: RouteLocationNormalizedLoaded,callback?: () => void) {
    if (view === undefined) {

      const {visitedViews:visitedViews} = useTagsViewStore().delView(router.currentRoute.value);
      const latestView = visitedViews.slice(-1)[0]
      if (latestView) {
        return router.push(latestView.fullPath)
      }
      return router.push('/')
      
    }
    useTagsViewStore().delView(view)
    callback?.()
  },




  // 关闭所有tab页签
  closeAllPage(callback?: () => void) {
    useTagsViewStore().delAllViews()
    callback?.()
  },
  // 关闭左侧tab页签
  closeLeftPage(view: RouteLocationNormalizedLoaded,callback?: () => void) {
    return useTagsViewStore().delLeftTags(view)
  },
  // 关闭右侧tab页签
  closeRightPage(obj) {
    return useTagsViewStore().delRightTags(obj || router.currentRoute.value)
  },
  // 关闭其他tab页签
  closeOtherPage(obj) {
    useTagsViewStore().delOthersViews(obj || router.currentRoute.value)
  },
  // 打开tab页签
  openPage(title, url, params) {
    console.log('tab.ts打开标签页',url,params)
    const obj = { path: url, meta: { title: title } }
    useTagsViewStore().addView(obj)
    return router.push({ path: url, query: params })
  },
  // 修改tab页签
  updatePage(obj) {
    return useTagsViewStore().updateVisitedView(obj)
  }
}